<?php
declare(strict_types=1);
namespace cms\exam\admin\mvc_controller;

use cms\exam\service\TopicGroupService;
use cms\exam\service\TopicService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Exception\BadRequestHttpException;
use Hyperf\HttpServer\Annotation\AutoController;
use Psr\Http\Message\ResponseInterface;

/**
 *
 * Class TopicController
 * @package cms\exam\admin\mvc_controller
 * @AutoController(prefix="mvc/exam/admin_topic")
 */
class TopicController extends CommonController
{
    /**
     * @Inject()
     * @var TopicService
     */
    protected TopicService $topicService;

    /**
     * @Inject()
     * @var TopicGroupService
     */
    protected TopicGroupService $topicGroupService;
    /**
     * @return ResponseInterface
     */
    public function retrieve(): ResponseInterface
    {
        $app = $this->_getApp(true);
        $group_id = (int) $this->request->input('group_id', 0);
        $group = $this->topicGroupService->getDataById($group_id);
        return $this->template([
            'app' => $app,
            'group' => $group,
        ]);
    }

    /**
     * @return ResponseInterface
     */
    public function create(): ResponseInterface
    {
        // 站点
        $app = $this->_getApp(true);
        $group_id = (int) $this->request->input('group_id', 0);
        $group = $this->topicGroupService->getDataById($group_id);
        // 题型
        $type = $this->topicService->readSetting('topic')->get('type');
        return $this->template([
            'app' => $app,
            'group' => $group,
            'type' => $type,
        ], 'form');
    }

    /**
     * @return ResponseInterface
     */
    public function update(): ResponseInterface
    {
        $id = (int) $this->request->input('id', 0);
        $data = $this->topicService->getDataById($id);
        // 题型
        $type = $this->topicService->readSetting('topic')->get('type');
        foreach ($data->content as $k => $v) {
            if (array_key_exists($k, $type[$data->type]['field'])) {
                $type[$data->type]['field'][$k]['value'] = $v;
            }
        }
        return $this->template([
            'app' => $data->app,
            'type' => $type,
            'data' => $data
        ], 'form');
    }

    /**
     * @return ResponseInterface
     */
    public function detail(): ResponseInterface
    {
        $id = (int) $this->request->input('id', 0);
        $data = $this->topicService->getDataById($id, true);
        // 题型
        $type = $this->topicService->readSetting('topic')->get('type');
        foreach ($data->content as $k => $v) {
            if (array_key_exists($k, $type[$data->type]['field'])) {
                $type[$data->type]['field'][$k]['value'] = $v;
            }
        }

        return $this->template([
            'app' => $data->app,
            'type' => $type,
            'data' => $data
        ]);
    }
}